package cn.webrx.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@MapperScan("cn.webrx.mapper")
@PropertySource("db.properties")
@ComponentScan("cn.webrx.mapper")
public class SpringConfig {
    @Value("${db.url}")
    private String url;

    @Value(("${db.username}"))
    private String username;

    @Bean(name = "ds", destroyMethod = "close", initMethod = "init")
    public DruidDataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        return ds;
    }

    @Bean("sf")
    public MybatisSqlSessionFactoryBean sf(@Qualifier("ds") DataSource ds) {
        var sf = new MybatisSqlSessionFactoryBean();
        sf.setDataSource(ds);

        GlobalConfig cfg = new GlobalConfig();
        cfg.setBanner(false);

        sf.setGlobalConfig(cfg);

        sf.setMapperLocations(resolveMapperLocations());
        return sf;
    }

    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath*:mapper/*Mapper*.xml");
        //mapperLocations.add("classpath*:com/pab/cc/ces/mapper/*Mapper*.xml");
        //mapperLocations.add("classpath*:com/pab/cc/ams/mapper/*Mapper*.xml");
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }
}
